<template>
  <div id="userPassport">
    <a-form
      :style="{ maxWidth: 480, margin: '0 auto' }"
      label-align="left"
      :model="formState"
      name="basic"
      :label-col="{ span: 4 }"
      :wrapper-col="{ span: 22 }"
      autocomplete="off"
      @finish="handleSubmit"
    >
      <a-form-item
        label="手机号"
        name="phone"
        :rules="[
          { required: true, message: '请输入手机号' },
          { min: 11, max: 11, message: '请输入正确的手机号' },
        ]"
      >
        <a-input v-model:value="formState.phone" placeholder="请输入手机号" />
      </a-form-item>

      <a-form-item
        label="密码"
        name="password"
        :rules="[
          { required: true, message: '请输入密码' },
          { min: 8, message: '密码长度不能小于8位' },
        ]"
      >
        <a-input-password
          v-model:value="formState.password"
          placeholder="请输入密码"
        />
      </a-form-item>
      <a-form-item
        label="确认密码"
        name="checkPassword"
        :rules="[
          { required: true, message: '请输入确认密码' },
          { min: 8, message: '密码长度不能小于8位' },
        ]"
      >
        <a-input-password
          v-model:value="formState.checkPassword"
          placeholder="请输入确认密码"
        />
      </a-form-item>
      <a-form-item
        :wrapper-col="{ offset: 4, span: 16 }"
        style="text-align: center"
      >
        <a-button type="primary" html-type="submit" class="remit-button">
          注册
        </a-button>
      </a-form-item>
    </a-form>
  </div>
</template>
<script lang="ts" setup>
import { reactive } from "vue";
import { message } from "ant-design-vue";
import { userLogin, userRegister } from "@/api/user";
import { useRouter } from "vue-router";
import { useLoginUserStore, useAuthStore } from "@/store/useLoginUserStore";

interface FormState {
  phone: string;
  password: string;
  checkPassword: string;
}

const formState = reactive<FormState>({
  phone: "",
  password: "",
  checkPassword: "",
});
const authStore = useAuthStore();
const router = useRouter();
const userLoginStore = useLoginUserStore();
const handleSubmit = async (values: any) => {
  if (values.password !== values.checkPassword) {
    message.error("两次输入的密码不一致");
    return;
  }
  const res = await userRegister(values);
  console.log(res);
  //注册成功  跳转
  if (res.data.code === 200) {
    message.success("注册成功");
    const res = await userLogin({
      phone: values.phone,
      password: values.password,
    });
    console.log(res);
    if (res.data.code === 200) {
      await userLoginStore.fetchLoginUser();
      message.success("登录成功");
      const token = res.data.data.tokenValue;
      localStorage.setItem("token", token);
      authStore.closeLoginModal();
    }
  } else {
    message.error("手机号已存在，请登录");
  }
};
</script>

<style scoped>
#userPassport .title {
  text-align: center;
  margin-bottom: 16px;
}

#userPassport .text-p {
  text-align: center;
  margin-bottom: 16px;
}
</style>
